package com.ls.fw.token.handler.impl;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;

import com.ls.fw.token.annotation.RequireToken;
import com.ls.fw.token.handler.HttpTokenHandler;
import com.ls.fw.token.service.TokenManager;
import com.ls.fw.token.support.TokenRepository;


/**
 * token處理器
 * 
 * @author lisheng
 * @date 2015年12月24日 下午6:36:31
 * @version V1.0
 */
public class DefaultTokenHandler2Impl implements HttpTokenHandler{

	private TokenManager tokenManager;

	@Override
	public boolean checkToken(HttpServletRequest request, String token) {
		String requestToken = this.decodeToken(token, request);
		String sessionToken = this.getToken(request, token, false);
		 if (StringUtils.isNotBlank(sessionToken)
				 && sessionToken.equals(requestToken)) {
			 return true;
		 }
		 return false;
	}

	@Override
	public String createToken(HttpServletRequest request,
			HttpServletResponse response, String token) {
		return tokenManager.createToken(this.getKey(request, token));
	}

	@Override
	public void removeToken(HttpServletRequest request,
			HttpServletResponse response, String token) {
		if(StringUtils.isNotBlank(token)){
		     this.tokenManager.delRelationshipByToken(token);
		}else{
			tokenManager.delRelationshipByKey(this.getKey(request, token));
		}
	}

	@Override
	public String getToken(HttpServletRequest request, String token,boolean createIFNoExist) {
		String t = tokenManager.getToken(this.getKey(request, token), createIFNoExist);
		if(createIFNoExist && StringUtils.isBlank(t)){
			t = this.tokenManager.createToken(this.getKey(request, token));
		} 
		return t;
	}

	@Override
	public void success(HttpServletRequest request,
			HttpServletResponse response, String token, RequireToken chekToken) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void fail(HttpServletRequest request, HttpServletResponse response,
			String token) throws IOException {
		// TODO Auto-generated method stub
		
	}

	@Override
	public String decodeToken(String baseToken, HttpServletRequest request) {
		 String _token = tokenManager.decodeToken(baseToken, request);
	     return _token;
	}


	@Override
	public String getKey(HttpServletRequest request, String token) {
		return request.getSession().getId();
	}

	@Override
	public TokenRepository getTokenRepository() {
		// TODO Auto-generated method stub
		return null;
	}
}
